package cn.cp.baseframe.service.impl;

import cn.cp.baseframe.mapper.UserMapper;
import cn.cp.baseframe.model.domain.UserDO;
import cn.cp.baseframe.model.dto.UserDTO;
import cn.cp.baseframe.model.req.UserReq;
import cn.cp.baseframe.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenchaoqi
 * @since 2022-03-13
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;


    @Override
    public List<UserDTO> query() {
        List<UserDO> userList = userMapper.query();
        List<UserDTO> result = new ArrayList<>();
        for (UserDO u : userList) {
            UserDTO userDTO = new UserDTO();
            userDTO.setAge(u.getAge());
            userDTO.setId(u.getId());
            userDTO.setName(u.getName());
            result.add(userDTO);
        }
        return result;
    }

    @Override
    public List<UserDTO> page(Integer pageIndex, Integer pageSize) {
        //计算起始页
        Integer startIndex = (pageIndex-1)*pageSize;
        List<UserDO> userList = userMapper.page(startIndex,pageSize);
        List<UserDTO> result = new ArrayList<>();
        for (UserDO u : userList) {
            UserDTO userDTO = new UserDTO();
            userDTO.setAge(u.getAge());
            userDTO.setId(u.getId());
            userDTO.setName(u.getName());
            result.add(userDTO);
        }
        return result;
    }

    @Override
    public Integer insert(UserReq req) {
        UserDO userDO = new UserDO();
        userDO.setId(req.getId());
        userDO.setAge(req.getAge());
        userDO.setName(req.getName());
        return userMapper.insert(userDO);
    }

    @Override
    public Integer update(UserReq req) {
        UserDO userDO = new UserDO();
        userDO.setId(req.getId());
        userDO.setAge(req.getAge());
        userDO.setName(req.getName());
        return userMapper.update(userDO);
    }

    @Override
    public Integer delete(Integer id) {
        return userMapper.delete(id);
    }
}
